# https://jumpserver.9981.team/api/docs
# https://docs.jumpserver.org/zh/master/dev/rest_api/

import requests
import json
import sys
import csv

JmsToken = 'xxxxxxxxxxxxxxxxxxxxxxxx'
JmsBaseApi = "https://xxxxxxxxxxxxxx.com"

# 此类做token 是否可用判断以及涉及post方法的处理
# get 获取jms状态判断
# post 对jms进行改动操纵
class HTTP(object):
    def __init__(self, *args):
        server = None
        token = None
        token_status = False

    # token可用性判断
    @classmethod
    def check_token(cls, server, token):
        uri = "/api/v1/users/users"
        url = server + uri
        print(url)
        headers = {
            'Authorization': 'token ' + token, 
            # 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002',
            'content-type': "application/json"
        }
        res = requests.get(url, headers=headers)
        if res.status_code == 200:
            cls.server = server
            cls.token = token
            cls.token_status = True
            # print(res.text)
            print("token 正常")

        else:
            print("token 不可用")
            # print(res.text)
            sys.exit()
        print(cls.server, cls.token, cls.token_status)

    # get方法获取jms信息
    @classmethod
    def get(cls, uri, data=None, *args, **kwargs):
        if cls.token_status == True:
            url = cls.server + uri
            headers = {
                'Authorization': 'token ' + cls.token, 
                # 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002',
                'content-type': "application/json"
            }
            res = requests.get(url, headers=headers, params=data)
        else:
            print("token 不可用")
            sys.exit()
        return res

    # post方法获取jms信息或操作jms
    @classmethod
    def post(cls, uri, data=None, *args, **kwargs):
        if cls.token_status == True:
            url = cls.server + uri
            headers = {
                'Authorization': 'token ' + cls.token, 
                # 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002',
                'content-type': "application/json"
            }
            data = json.dumps(data)
            print(data)
            res = requests.post(url, headers=headers, data=data)
            print("post 结果", res.status_code, res.json())
        else:
            print("token 不可用")
            sys.exit()
        return res

# 资产列表节点管理
# 判断节点是否存在
# 节点不存在则创建
class NODE(object):
    def __init__(self, *args):
        self.id = None
        # self.node_full_name = None
        self.name = None
    
    # 判断资产节点是否存在，存在则获取资产节点id，若不存在则新建资产节点并获取id
    def exist(self, name):
        uri = "/api/v1/assets/nodes/"
        self.name = name
        # self.node_full_name = full_name
        # self.name = self.node_full_name.split('/')[-1]

        # if self.node_full_name == self.name:
        #     print("输入资产节点名字不合规")
        #     sys.exit()

        data = { "value": self.name
        }
        res = HTTP.get(uri, data)
        res_data = res.json()
        if res.status_code == 200 and res_data:
            print("资产节点 {} 已经存在".format(self.name))
            self.id = res_data[0].get('id')
            print(res_data)
            print(res.status_code, type(res_data))
        else:
            self.create()
            
    def create(self):
        print("创建资产节点 {}".format(self.name))
        data = { 
            "value": self.name
        }
        uri = "/api/v1/assets/nodes/"
        res = HTTP.post(uri, data)
        print(res.status_code, res.json())
        self.id = res.json().get('id')

# 用户组管理
class UserGroup(object):
    def __init__(self, *args):
        self.id = None
        # self.node_full_name = None
        self.UserGroupName = None

    def exist(self, UserGroupName):
        uri = "/api/v1/users/groups/"
        self.UserGroupName =UserGroupName

        data = { "name": self.UserGroupName
        }
        res = HTTP.get(uri, data)
        res_data = res.json()
        if res.status_code == 200 and res_data:
            print("用户组 {} 已经存在".format(self.UserGroupName))
            self.id = res_data[0].get('id')
            print(res_data)
            print(res.status_code, type(res_data))
        else:
            self.create()
            # pass
            
    def create(self):
        print("创建用户组 {}".format(self.UserGroupName))
        data = { 
            "name": self.UserGroupName
        }
        uri = "/api/v1/users/groups/"
        res = HTTP.post(uri, data)
        print(res.status_code, res.json())
        self.id = res.json().get('id')
        

# 判断必须的系统用户是否存在，不存在则创建
class SystemUser(object):
    def __init__(self, *args):
        self.id = None
        self.name = "common3"
    
    # 检查系统用户是否存在
    def exist(self):
        uri = "/api/v1/assets/system-users/"
        data = {
            "name": self.name
        }
        res = HTTP.get(uri, data)
        res_data = res.json()
        if res.status_code in [200, 201] and res_data:
            print("系统用户已存在")
            print(res_data)
            self.id = res_data[0].get('id')
        else:
            # self.create()
            print("系统用户需要新建")
            # pass
            self.create()
    
    # 新建系统通用用户
    def create(self):
        print("创建系统用户 {}".format(self.name))
        uri = '/api/v1/assets/system-users/'
        data = {
            'name': self.name,
            'login_mode': 'manual',
            'protocol': 'ssh',
            "comment": "Linux 通用用户"
        }
        res = HTTP.post(uri, data)
        self.id = res.json().get('id')
        print(self.id)


# 资产授权规则 需要用户组id 资产节点id 系统用户id
class AssetPermission(object):
    def __init__(self, *args):
        self.id = None
        self.rulename = None
        self.user_group_id = None
        self.node_id = None
        self.system_user_id = None

    # 判断资产规则是否存在
    def exist(self, rulename, user_group_id, node_id, system_user_id):
        self.rulename = rulename
        self.user_group_id = user_group_id
        self.node_id = node_id
        self.system_user_id = system_user_id
        uri = "/api/v1/perms/asset-permissions/"
        data = {
            "name": self.rulename
        }
        res = HTTP.get(uri, data)
        res_data = res.json()
        if res.status_code in [200, 201] and res_data:
            print(res.status_code, res_data)
            self.id = res_data[0].get('id')
        else:
            # self.create()
            print("资产规则不存在，需要新建")
            self.create()

    # 创建资产授权规则
    def create(self):
        print("创建资产授权名称 {}".format(self.rulename))
        uri = '/api/v1/perms/asset-permissions/'
        data = {
            "name": self.rulename,
            "user_groups": [self.user_group_id],
            "nodes": [self.node_id],
            "system_users": [self.system_user_id],
            "actions": ["all"],
            "is_active": True
        }
        res = HTTP.post(uri, data)
        res_data = res.json()
        if res.status_code in [200, 201] and res_data:
            print("创建资产授权规则成功: ", res_data)
        else:
            print("创建授权规则失败: ", res_data)


# 判断资产是否存在以及创建资产
class ASSET(object):
    def __init__(self, *args):
        self.id           = None
        self.name         = None
        self.ip           = None
        self.platform     = None
        self.protocols    = None
        self.node_name    = None
        self.active       = None
        self.port         = None
        self.protocol     = "ssh"
        # self.admin_user   = AdminUser()
        self.node         = NODE()
        self.usergroup    = UserGroup()
        self.systemuser   = SystemUser()
        self.assetPermission = AssetPermission()

    # 判断资产是否已经存在
    def exist(self, assetsinfo):
        self.name = assetsinfo[0]
        self.ip = assetsinfo[1]
        self.platform = assetsinfo[2]
        self.protocol = assetsinfo[5]
        self.port = assetsinfo[4]
        self.node_name = assetsinfo[7]
        self.active = assetsinfo[3]
        # self.protocols = ['ssh/22' if self.platform == 'Linux' else  'rdp/3389']

        uri = "/api/v1/assets/assets/"
        data = {
            "hostname": self.name
        }
        res = HTTP.get(uri, data)
        res_data = res.json()
        if res.status_code in [200, 201] and res_data:
            print(res_data)
            print('资产 {} 已存在'.format(self.name))
            self.id = res_data[0].get('id')
            print(self.id)
        else:
            print(res_data)
            print("即将新建")
            self.create()

    # 当资产不存在时创建资产
    def create(self):
        print("新建资产 {} ".format(self.name))
        self.node.exist(self.node_name)
        self.usergroup.exist(self.node_name)
        self.systemuser.exist()
        self.assetPermission.exist(self.node_name, self.usergroup.id, self.node.id, self.systemuser.id)

        uri = "/api/v1/assets/assets/"
        data = {
            "hostname": self.name,
            "ip": self.ip,
            "platform": self.platform,
            # "protocols": self.protocols,
            "port": self.port,
            "protocol": self.protocol,
            "nodes": [self.node.id],
            "is_active": True
        }
        res = HTTP.post(uri, data)
        self.id = res.json().get('id')
        print(self.id)


        

HTTP.check_token(JmsBaseApi, JmsToken)
print(HTTP.token_status, HTTP.token, HTTP.server)

# check_usergropu = UserGroup()
# check_usergropu.exist('test11')
# asper = AssetPermission()
# asper.exist('rule100')

# SysUserMange = SystemUser()
# SysUserMange.exist()

# node_check = NODE()
# node_check.exist('node1')
# node_check.exist('test1000')
# assert_check = ASSET()
# assert_check.exist('k8s-node3')

with open('host.csv', 'r') as f:
    reader = csv.reader(f)
    print(type(reader))

    assert_change = ASSET()
    for row in reader:
        assert_change.exist(row)
    

